import requests
import os
import shutil
from lxml import etree


url = "https://www.taptap.cn/top/played"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/000000000 Safari/537.36 Edg/000000000",


}
res = requests.get(url, headers=headers)

tap_path = "static/tap"
if not os.path.exists(tap_path):
    os.makedirs(tap_path)
else:
    shutil.rmtree(tap_path)
    os.mkdir(tap_path)

tree = etree.HTML(res.text)

# print(res.text)
names = tree.xpath('//div[@class="game-center"]//span[@class="text text-default--size"]/text()')
imgs = tree.xpath('//div[@class="list-item"]//img[@class="tap-image app-icon__img"]/@src')

print(names,imgs)
dict1 = dict(zip(names, imgs))
# 用 zip(names, imgs) 把 names（键）和 imgs（值）按索引一一配对，形成元组组合。
# 用 dict() 函数将配对后的结果直接转换成字典。
print(dict1)

for name, img in dict1.items():
    with open(f"{tap_path}/{name}.jpg", "wb") as f:
        f.write(requests.get(img).content)



# urls = [f"https://www.taptap.cn/webapiv2/app-top/v2/hits?from={page}&limit=10&type_name=pop&X-UA=V%3D1%26PN%3DWebApp%26LANG%3Dzh_CN%26VN_CODE%3D102%26LOC%3DCN%26PLT%3DPC%26DS%3DAndroid%26UID%3D819cfabb-20de-4a2d-9696-28c3cf0f6991%26OS%3DWindows%26OSV%3D10%26DT%3DPC" for page in range(10,40,10)]
# headers = {
#     "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/000000000 Safari/537.36 Edg/000000000",
#
#
# }
# tap_path = "static/tap"
# if not os.path.exists(tap_path):
#     os.makedirs(tap_path)
# else:
#     shutil.rmtree(tap_path)
#     os.mkdir(tap_path)
#
# for url in urls:
#     # print(url)
#     res = requests.get(url,headers=headers)
#
#     print(res.status_code)
#     datas = res.json()["data"]["list"]
#     for data in datas:
#         # print(data["app"])
#         name = data["app"]["title"]
#         img = data["app"]["icon"]["url"]
#         duct1 = {
#             "游戏名": name,
#             "图片地址": img
#         }
#         print(duct1)
#         with open(f"{tap_path}/{name}.jpg", "wb") as f:
#             f.write(requests.get(img).content)
#     print("--------------------------------------------")


